import React, { useState, useEffect, useCallback, useMemo } from "react";
import {
  View,
  Text,
  TouchableOpacity,
  Modal as RNModal,
  TouchableWithoutFeedback,
  SafeAreaView,
  ScrollView,
} from "react-native";
import { useTheme } from "@/contexts/ThemeContext";
import { Ionicons } from "@expo/vector-icons";
import { Avatar } from "@rneui/themed";
import FriendsStateStore from "@/store/friend";
import { getFriendList } from "@/services/api/friend";
import GroupMembersList from "../components/MemberList";
import StatusDialog from "@/components/Global/Dialog";
import AlertService from "@/components/Global/Alert/service";
import {
  GroupMember,
  GroupMembersListMode,
  GroupMemberRole,
  RemoveMembersModalProps,
} from "@/types/group-chat";
import { createStyles } from "./index.style";

// 模拟群成员数据，实际应用中应从API或store获取
const mockMembers: GroupMember[] = [
  {
    id: "1",
    avatar: "https://randomuser.me/api/portraits/men/1.jpg",
    nickname: "挽",
    friendStatus: 1,
    createTime: "2023-01-01",
    uuid: "uuid1",
    remark: "老朋友",
    lastOnlineTime: null,
    groupRemark: "挽哥", // 群聊备注
    role: GroupMemberRole.OWNER, // 群主
  },
  {
    id: "2",
    avatar: "https://randomuser.me/api/portraits/women/2.jpg",
    nickname: "村幼",
    friendStatus: 1,
    createTime: "2023-01-02",
    uuid: "uuid2",
    remark: "幼幼",
    lastOnlineTime: null,
    groupRemark: "", // 无群聊备注
    role: GroupMemberRole.ADMIN, // 管理员
  },
  {
    id: "3",
    avatar: "https://randomuser.me/api/portraits/men/3.jpg",
    nickname: "苦瓜大王",
    friendStatus: 0,
    createTime: "2023-01-03",
    uuid: "uuid3",
    remark: "",
    lastOnlineTime: null,
    groupRemark: "瓜哥", // 群聊备注
    role: GroupMemberRole.MEMBER, // 普通成员
  },
  {
    id: "4",
    avatar: "https://randomuser.me/api/portraits/women/4.jpg",
    nickname: "静静",
    friendStatus: 1,
    createTime: "2023-01-04",
    uuid: "uuid4",
    remark: "静姐",
    lastOnlineTime: null,
    groupRemark: "静静姐", // 群聊备注
    role: GroupMemberRole.MEMBER, // 普通成员
  },
  {
    id: "5",
    avatar: "https://randomuser.me/api/portraits/men/5.jpg",
    nickname: "解木散",
    friendStatus: 0,
    createTime: "2023-01-05",
    uuid: "uuid5",
    remark: "",
    lastOnlineTime: null,
    groupRemark: "", // 无群聊备注
    role: GroupMemberRole.MEMBER, // 普通成员
  },
];

// 模拟群成员ID列表
const mockMemberIds = mockMembers.map((member) => member.id);

const RemoveMembersModal: React.FC<RemoveMembersModalProps> = ({
  visible,
  onClose,
  groupId = "",
  groupName = "",
  groupAvatar = "",
  groupMembers = mockMemberIds,
  isAdmin = true, // 默认设为管理员以便可以移除成员
  isOwner = false,
  onRemove,
}) => {
  const { colors } = useTheme();
  const [selectedMembers, setSelectedMembers] = useState<string[]>([]);
  const [dialogVisible, setDialogVisible] = useState(false);

  // 直接从store获取状态，避免使用hook
  const [friends, setFriends] = useState<GroupMember[]>([]);
  const [loading, setLoading] = useState(false);

  // 使用外部样式文件
  const styles = useMemo(
    () => createStyles(colors, selectedMembers),
    [colors, selectedMembers]
  );

  // 获取好友数据
  const loadFriends = useCallback(async () => {
    setLoading(true);
    try {
      // 直接使用模拟数据
      setFriends(mockMembers);
      setLoading(false);
    } catch (error) {
      console.error("加载好友数据失败:", error);
      setLoading(false);
    }
  }, []);

  // 优化的数据加载逻辑
  useEffect(() => {
    if (visible) {
      loadFriends();
    }

    // 关闭时重置选择状态
    return () => {
      if (!visible) {
        setSelectedMembers([]);
      }
    };
  }, [visible, loadFriends]);

  // 处理成员选择
  const handleSelectMember = useCallback((memberId: string) => {
    setSelectedMembers((prev) => {
      if (prev.includes(memberId)) {
        return prev.filter((id) => id !== memberId);
      } else {
        return [...prev, memberId];
      }
    });
  }, []);

  // 显示确认对话框
  const showConfirmDialog = useCallback(() => {
    if (selectedMembers.length === 0) return;
    setDialogVisible(true);
  }, [selectedMembers]);

  // 确认移除成员
  const confirmRemove = useCallback(() => {
    if (selectedMembers.length === 0) return;

    // 关闭确认对话框
    setDialogVisible(false);

    if (onRemove) {
      onRemove(selectedMembers);
    }

    // 显示成功提示
    AlertService.showAlert(
      "success",
      `成功移除 ${selectedMembers.length} 位成员`
    );

    // 重置状态并关闭模态框
    setSelectedMembers([]);
    onClose();
  }, [selectedMembers, onRemove, onClose]);

  // 取消移除操作
  const cancelRemove = useCallback(() => {
    setDialogVisible(false);
  }, []);

  // 取消选择某个成员
  const handleUnselectMember = useCallback((memberId: string) => {
    setSelectedMembers((prev) => prev.filter((id) => id !== memberId));
  }, []);

  // 获取已选择的成员数据
  const selectedMemberData = useMemo(() => {
    return selectedMembers
      .map((id) => friends.find((friend) => friend.id === id))
      .filter(Boolean) as GroupMember[];
  }, [selectedMembers, friends]);

  // 过滤出只有群成员的好友列表
  const groupMemberFriends =
    friends?.filter((friend) => groupMembers.includes(friend.id)) || [];

  return (
    <RNModal
      visible={visible}
      transparent={true}
      animationType="slide"
      onRequestClose={onClose}
      statusBarTranslucent={true}
    >
      <SafeAreaView style={styles.modalContainer}>
        <TouchableWithoutFeedback onPress={onClose}>
          <View style={styles.backdrop} />
        </TouchableWithoutFeedback>

        <View style={styles.modalContent}>
          {/* 标题栏 */}
          <View style={styles.header}>
            <TouchableOpacity onPress={onClose} style={styles.closeButton}>
              <Ionicons name="close" size={24} color={colors.text.primary} />
            </TouchableOpacity>

            <Text style={[styles.title, { color: colors.text.primary }]}>
              移除群聊成员
            </Text>

            <TouchableOpacity
              onPress={showConfirmDialog}
              style={[
                styles.removeButton,
                selectedMembers.length === 0 && styles.disabledButton,
              ]}
              disabled={selectedMembers.length === 0}
            >
              <Text
                style={[
                  styles.removeButtonText,
                  selectedMembers.length === 0 && styles.disabledButtonText,
                ]}
              >
                移除
              </Text>
            </TouchableOpacity>
          </View>

          {/* 群聊信息 */}
          {groupName && (
            <View style={styles.groupInfo}>
              <Avatar
                rounded
                size={50}
                source={{
                  uri:
                    groupAvatar ||
                    "https://randomuser.me/api/portraits/men/32.jpg",
                }}
                containerStyle={styles.groupAvatar}
              />

              <View style={styles.groupTextInfo}>
                <Text
                  style={[styles.groupName, { color: colors.text.primary }]}
                >
                  {groupName}
                </Text>

                <Text
                  style={[
                    styles.groupMemberCount,
                    { color: colors.text.secondary },
                  ]}
                >
                  {groupMembers.length}名群成员
                </Text>
              </View>
            </View>
          )}

          {/* 已选择计数 */}
          <View style={styles.selectedCount}>
            <Text
              style={[
                styles.selectedCountText,
                { color: colors.text.secondary },
              ]}
            >
              {selectedMembers.length > 0
                ? `已选择 ${selectedMembers.length} 位成员`
                : "请选择要移除的成员"}
            </Text>
          </View>

          {/* 已选择成员预览 */}
          {selectedMembers.length > 0 && (
            <View style={styles.selectedPreviewContainer}>
              <Text style={styles.selectedPreviewTitle}>将要移除的成员:</Text>
              <ScrollView
                horizontal={true}
                showsHorizontalScrollIndicator={false}
                style={styles.selectedPreviewScroll}
              >
                {selectedMemberData.map((member) => (
                  <View key={member.id} style={styles.selectedMemberItem}>
                    <View style={styles.avatarContainer}>
                      <Avatar
                        rounded
                        size={50}
                        source={{
                          uri:
                            member.avatar ||
                            "https://randomuser.me/api/portraits/men/32.jpg",
                        }}
                      />
                      <TouchableOpacity
                        style={styles.removeIconContainer}
                        onPress={() => handleUnselectMember(member.id)}
                      >
                        <Ionicons name="close" size={14} color="#fff" />
                      </TouchableOpacity>
                    </View>
                    <Text style={styles.selectedMemberName} numberOfLines={1}>
                      {member.groupRemark || member.remark || member.nickname}
                    </Text>
                  </View>
                ))}
              </ScrollView>
            </View>
          )}

          {/* 成员列表 */}
          <View style={styles.listContainer}>
            <GroupMembersList
              mode={GroupMembersListMode.REMOVE}
              friends={groupMemberFriends}
              loading={loading}
              selectedIds={selectedMembers}
              onSelectItem={handleSelectMember}
              groupMembers={groupMembers}
              isAdmin={isAdmin}
              isOwner={isOwner}
            />
          </View>
        </View>
      </SafeAreaView>

      {dialogVisible && (
        <StatusDialog
          visible={dialogVisible}
          type="warning"
          message={{
            title: "确认移除成员",
            content: "", // 不在这里提供内容，避免重复
          }}
          showCancelButton={true}
          onClose={cancelRemove}
          onConfirm={confirmRemove}
          onCancel={cancelRemove}
        >
          <Text style={{ fontSize: 14, color: colors.text.primary }}>
            确定要移除 {selectedMembers.length} 位成员吗？
          </Text>
        </StatusDialog>
      )}
    </RNModal>
  );
};

export default RemoveMembersModal;
